<template>
  <div class="signStyle">
    <!-- #ifndef MP-ALIPAY -->
    <!-- <div class="title">
			<u-icon name="none"></u-icon>
		</div> -->
    <div class="title">
      <u-icon name="close" @click="toIndex"></u-icon>
    </div>
    <!-- #endif -->
    <div class="loginBox">
      <h1 class="welcome">{{ $t("login.welcome") }}</h1>
      <div class="login-tab">
          <div :class="{current: loginType == 1}" @click="onLoginType(1)">短信登录</div>
          <div :class="{current: loginType == 2}" @click="onLoginType(2)">密码登录</div>
      </div>
      <div :class="['phone', 'style1']">
        <input
          type="number"
          v-model="phone"
          :style="[inputStyle]"
          :placeholder="$t('login.phone')"
        />
        <u-icon
          name="close"
          style="color: #ccc; font-size: 32rpx"
          :style="[inputStyle]"
          @click="phone = ''"
        >
        </u-icon>
      </div>
      <div class="password">
        <template v-if="loginType == 1">
          <input
            style="flex: 1; width: 0"
            type="number"
            v-model="code"
            :placeholder="$t('login.code')"
          />
          <div style="color: #f60313" @click="getOption">
            {{ tips }}
          </div>
        </template>
        <template v-else>
            <input
              type="text"
              v-model="password"
              :style="[inputStyle]"
              placeholder="请输入密码"
            />
            <u-icon
              name="close"
              style="color: #ccc; font-size: 32rpx"
              :style="[inputStyle]"
              @click="password = ''"
            >
            </u-icon>
        </template>
      </div>
      <div class="warning">
        <view class="radio">
          <radio
            :checked="read"
            color="#f0250e"
            @click="read = !read"
            style="transform: scale(0.7)"
          />
        </view>
        <view class="content">
          <span>{{ $t("login.warning1") }}</span>
          <span>
            <text
              style="color: #007aff"
              @click.stop="
                $utils.toUrl(
                  '/user/my/article-detail?id=' + stores.client_service_id
                )
              "
              >《用户服务协议》</text
            >
            及<text
              style="color: #007aff"
              @click.stop="
                $utils.toUrl(
                  '/user/my/article-detail?id=' + stores.client_privacy_id
                )
              "
              >《平台隐私政策》，</text
            >
          </span>
          <span>{{ $t("login.register") }}</span>
        </view>
      </div>
      <div class="btn disabled" v-if="!read">
        {{ $t("login.loginBtn") }}
      </div>
      <div class="btn" v-else @click="loginAction">
        {{ $t("login.loginBtn") }}
      </div>
      <!-- #ifndef H5 -->
      <div class="others" v-if="false">
        <div class="title">
          <span></span>
          <span>{{ $t("login.others") }}</span>
          <span></span>
        </div>
        <div class="methods">
          <div class="method" @click="toBind('weixin')">
            <div class="pic">
              <image :src="asyncImgs.login.wechat" alt="" mode="aspectFill" />
            </div>
            <span>{{ $t("login.weChat") }}</span>
          </div>
          <!-- <div class="method" v-if="param.qq && param.qq.use == 1">
            <div class="pic">
              <image
                :src="param.qq.picUrl"
                alt=""
                mode="aspectFill"
                v-if="param.qq && param.qq.picUrl != ''"
              />
              <image :src="asyncImgs.login.wechat" alt="" mode="aspectFill"/>
            </div>
            <span>QQ登录</span>
          </div> -->
        </div>
      </div>
      <!-- #endif -->
      <!-- #ifdef APP-PLUS -->
      <button
        v-if="systemInfo.osName == 'ios'"
        style="margin-top: 40rpx"
        class="applebtn btn"
        open-type="login"
        @click="appAppleLogin('apple')"
      >
        <text
          class="iconfont icon-apple"
          style="
            color: #fff;
            font-size: 40rpx;
            font-weight: 400;
            margin-right: 14rpx;
          "
        ></text>
        通过Apple登录
      </button>
      <!-- #endif -->
    </div>
    <BindRelationH5 ref="BindRelation" @login="getCode"></BindRelationH5>
  </div>
</template>

<script>
import { getRedirectUri } from "@/api/login";
import BindRelationH5 from "./BindRelationH5";
import { getStoreSwitch } from "@/api/system";

export default {
  props: {
    param: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  components: {
    BindRelationH5
  },
  data() {
    return {
      tips: this.$t("login.getCode"),
      seconds: 60,
      phone: "",
      password: "",
      code: "",
      read: false,
      loginCode: "",
      loginType: 1, // 1: 短信登录,2: 密码登录
    };
  },
  computed: {
    inputStyle() {
      return {
        color: "#262626",
        fontWeight: "500;"
      };
    },
    noLoginTabarPath() {
      return this.$store.getters.noLoginTabarPath;
    },
    routeType() {
      return this.$store.getters.routeType;
    },
    systemInfo() {
      return uni.getSystemInfoSync();
    }
  },
  methods: {
    onLoginType(type) {
        this.loginType = type;
    },
    async getOption() {
      const myreg = /^1[3-9]\d{9}$/;
      if (!this.phone) {
        uni.showToast({
          title: this.$t("login.inputPhone"),
          icon: "none",
          duration: 1000
        });
        return false;
      }
      if (!myreg.test(this.phone)) {
        uni.showToast({
          title: this.$t("login.inputPhoneNumber"),
          icon: "none",
          duration: 1000
        });
        return false;
      }
      const share_user_id = uni.getStorageSync("parent_user_id");
      let result = await this.$allrequest.user.getOptionByH5({
        mobile: this.phone,
        share_user_id: share_user_id
      });
      if (
        result.data.is_exist_user === 0 &&
        result.data.enforce_bind_parent === 1
      ) {
        if (result.data.parent_id > 0 && result.data.parent_mobile) {
          this.$refs["BindRelation"].parent_avatar =
            result.data.parent_avatar_url;
          this.$refs["BindRelation"].parent_nickname =
            result.data.parent_nickname;
          this.$refs["BindRelation"].parent_mobile = result.data.parent_mobile;
          this.$refs["BindRelation"].parent_id = result.data.parent_id;
        }
        this.$refs["BindRelation"].showPopup = true;
      } else {
        this.getCode();
      }
    },
    async loginAction() {
      const myreg = /^1[3-9]\d{9}$/;
      if (!this.phone) {
        uni.showToast({
          title: this.$t("login.inputPhone"),
          icon: "none",
          duration: 1000
        });
        return false;
      }
      if (!myreg.test(this.phone)) {
        uni.showToast({
          title: this.$t("login.inputPhoneNumber"),
          icon: "none",
          duration: 1000
        });
        return false;
      }
      if (!this.code && this.loginType == 1) {
        uni.showToast({
          title: this.$t("login.inputCode"),
          icon: "none",
          duration: 1000
        });
        return false;
      }
      if (!this.password && this.loginType == 2) {
        uni.showToast({
          title: '请输入密码',
          icon: "none",
          duration: 1000
        });
        return false;
      }
      try {
        const share_user_id = uni.getStorageSync("parent_user_id");
        const page_type = uni.getStorageSync("page_type");
        let result = await this.$allrequest.user.user_login({
          phone: this.phone,
          verify_code: this.code,
          login_type: this.loginType,
          password: this.password,
          share_user_id: share_user_id ? share_user_id : 0,
          _platform: "phone",
          page_type,
          code: this.loginCode
        });

        // // #ifdef APP-PLUS
        // if (result.code == 0) {
        //   if (
        //     result.data.wechat_app_open_id == null ||
        //     result.data.wechat_app_open_id == ""
        //   ) {
        //     uni.login({
        //       provider: "weixin",
        //       scopes: "auth_base",
        //       success: (ress) => {
        //         uni.getUserInfo({
        //           provider: "weixin",
        //           lang: "zh_CN",
        //           success: (res) => {
        //             // uni.showToast({
        //             //   title: JSON.stringify(res),
        //             //   icon: "none",
        //             //   duration: 1000,
        //             // });
        //             uni.showToast({
        //               title: result.msg,
        //               icon: "none",
        //               duration: 1000,
        //             });
        //             setTimeout(() => {
        //               this.afterLogin(result, () => {
        //                 // this.$allrequest.user.updateUserWechatAppOpenId({
        //                 //   user_id: result.data.id,
        //                 //   open_id: res.userInfo.openId,
        //                 // }).then(res=>{
        //                 // });
        //               });
        //             }, 1000);
        //           },
        //           fail: (res) => {
        //             uni.showToast({
        //               title: JSON.stringify(res),
        //               icon: "none",
        //               duration: 1000,
        //             });
        //           },
        //         });
        //       },
        //       fail: (res) => {
        //         uni.showToast({
        //           title: JSON.stringify(res),
        //           icon: "none",
        //           duration: 1000,
        //         });
        //       },
        //     });
        //   } else {
        //     uni.showToast({
        //       title: result.msg,
        //       icon: "none",
        //       duration: 1000,
        //     });
        // 		setTimeout(() => {
        // 		  this.afterLogin(result);
        // 		}, 1000);
        //   }
        // } else {
        //   uni.showToast({
        //     title: result.msg,
        //     icon: "none",
        //     duration: 1000,
        //   });
        // }
        // // #endif
        // #ifdef H5
        if (this.$utils.isWechat()) {
          if (result.code == 0) {
            uni.removeStorageSync("hasUri");

            uni.showToast({
              title: result.msg,
              icon: "none",
              duration: 1000
            });
            setTimeout(() => {
              this.afterLogin(result);
            }, 1000);
          }
        } else {
          uni.showToast({
            title: result.msg,
            icon: "none",
            duration: 1000
          });
          setTimeout(() => {
            this.afterLogin(result);
          }, 1000);
        }
        // #endif
        // #ifndef H5
        uni.showToast({
          title: result.msg,
          icon: "none",
          duration: 1000
        });
        setTimeout(() => {
          this.afterLogin(result);
        }, 1000);
        // #endif
        // cid: plus.push.getClientInfo().clientid
      } catch (e) {
        uni.showToast({
          title: "登录失败",
          icon: "none",
          duration: 1000
        });
      }
    },
    async weiXinLogin(infoRes, code) {
      try {
        let result = await this.$allrequest.user.user_login({
          ...infoRes,
          user_info: infoRes.userInfo,
          encrypted_data: infoRes.encryptedData,
          _platform: "wx",
          code
        });
        uni.showToast({
          title: result.msg,
          icon: "none",
          duration: 1000
        });
        setTimeout(() => {
          this.afterLogin(result);
        }, 1000);
        // cid: plus.push.getClientInfo().clientid
      } catch (e) {}
    },
    async appWeixinLogin(infoRes) {
      try {
        let result = await this.$allrequest.user.user_login({
          ...infoRes,
          user_info: infoRes.userInfo,
          _platform: "app"
        });
        uni.showToast({
          title: result.msg,
          icon: "none",
          duration: 1000
        });
        setTimeout(() => {
          this.afterLogin(result);
        }, 1000);
        // cid: plus.push.getClientInfo().clientid
      } catch (e) {}
    },
    async appAppleLogin(provider) {
      uni.login({
        provider: provider,
        scopes: ["auth_user"],
        success: (res) => {
          uni.getUserInfo({
            provider: provider,
            success: async (userInfo) => {
              // if (userInfo.errMsg !== 'getUserInfo:ok')
              //   return uni.$u.toast(userInfo.errMsg);
              // // 服务发起登录
              // const param = {
              //   unionid: res.authResult.unionid,
              //   openid: res.authResult.openid,
              //   nickname: userInfo.userInfo.nickName,
              //   headimgurl: userInfo.userInfo.avatarUrl,
              //   // appcid: plus.push.getClientInfo().clientid,
              // };
              // }
            },
            fail: (fail) => {
              uni.showModal({
                content: JSON.stringify(fail),
                showCancel: false
              });
            }
          });
        },
        fail: (fail) => {
          uni.showModal({
            content: JSON.stringify(fail),
            showCancel: false
          });
        }
      });
    },
    async afterLogin(result, cb) {
      let hasOneStroe = false;

      if (result.code == 0) {
        uni.removeStorageSync("hasUri");
        uni.setStorageSync("token", result.data.access_token);
        uni.setStorageSync("userInfo", result.data);
        this.$store.commit("setUserInfo", result.data);
        uni.removeStorageSync("storeMdData");


        try {
          const res = await getStoreSwitch();
          if (res.data.is_switch_store) {
            uni.removeStorageSync("storeMdData");
            this.$store.commit("setStoreId", res.data.store_id);
            this.$store.commit("setCopyright", res.data.copyright);
            hasOneStroe = true;
            if (this.routeType) this.routeType = "reLaunch";
          }
        } catch (error) {}
        
        let newRouteType = this.routeType;
        if (cb) {
          cb();
        }
        if (this.noLoginTabarPath && this.routeType) {
          // #ifdef WEB
          newRouteType = "reLaunch";
          // #endif

          this.$utils.toUrl(this.noLoginTabarPath, newRouteType);
          setTimeout(() => {
            this.$store.commit("setNoLoginTabarPath", "");
            this.$store.commit("setRouteType", "");
          }, 0);
        } else {
          if (hasOneStroe) return this.$utils.toUrl("/pages/my/my", "reLaunch");
          this.$utils.goBack();
        }
      }
    },
    toBind(type) {
      // #ifdef APP-PLUS
      uni.login({
        provider: type,
        success: (loginRes) => {
          uni.getUserInfo({
            provider: type,
            success: (infoRes) => {
              if (type == "weixin") {
                this.appWeixinLogin(infoRes);
              } else {
                this.qqLogin(infoRes);
              }
            }
          });
        }
      });
      // #endif
      //getUserProfile仅支持微信小程序 app登录需条件编译登录逻辑 TODO
      // #ifdef MP-WEIXIN
      uni.getUserProfile({
        desc: "请求授权",
        success: (infoRes) => {
          uni.login({
            provider: type,
            success: (loginRes) => {
              if (type == "weixin") {
                this.weiXinLogin(infoRes, loginRes.code);
              } else {
                this.qqLogin(infoRes);
              }
            }
          });
        },
        fail: (res) => {
          this.$utils.toast(this.$t("login.fail"));
        }
      });
      // #endif
    },
    // 倒计时
    codeChange(text) {
      let start = text;
      this.tips = start + this.$t("diy.second");
      var setTime = setInterval(() => {
        start--;
        if (start <= 1) {
          clearInterval(setTime);

          this.tips = this.$t("login.getCode");
        } else {
          this.tips = start + this.$t("diy.second");
        }
      }, 1000);
    },
    // 获取验证码
    async getCode() {
      // 倒计时未结束
      if (this.tips != this.$t("login.getCode")) return;

      // #ifdef APP-PLUS || H5 || MP-TOUTIAO
      if (!this.$u.test.mobile(this.phone)) {
        return this.$u.toast(this.$t("login.inputPhoneNumber"));
      }

      // 向后端请求验证码
      let data = {
        phone: this.phone,
        code_type: "login"
      };
      try {
        const res = await this.$allrequest.user.sms_code(data);
        if (res.code != 0) throw new Error(res);
        // 开始倒计时60秒
        this.codeChange(60);
        uni.hideLoading();
      } catch (res) {
        uni.hideLoading();
        this.$u.toast(res.msg || this.$t("user.err"));
      }
      // #endif
    },
    toIndex() {
      this.$utils.goBack();
    },
    // 公众号授权操作
    webAuthorization() {
      window.location.href =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=sdfsdfgsaa194f7ca6" +
        "&redirect_uri=" +
        encodeURIComponent("http://sdfa.test.com/pages/login/login") +
        "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    }
  },

  async mounted() {
    // #ifdef WEB
    if (this.$utils.isWechat()) {
      if (this.$utils.getStorage("hasUri")) {
        let params = this.$utils.oneValues(window.location.href);
        this.loginCode = params.code;
        return;
      }

      const res = await getRedirectUri({
        path: "/login/login/login_page"
      });
      if (!res.code && res.data.uri) {
        this.$utils.setStorage("hasUri", true);
        window.location.href = res.data.uri;
      }
    }
    // #endif
  }
};
</script>

<style scoped lang="less">
.signStyle {
  width: 100%;
  height: 100vh;
  padding: 70rpx 50rpx 0 50rpx;
  background-color: #fff;
  .loginBox {
    margin-top: 130rpx;
    width: 100%;

    input {
      flex: auto;
      margin-right: 20rpx;
      height: 100%;
      border: none;
      background: none;
      list-style: none;
      font-size: 32rpx;
    }

    .phone {
      width: 100%;
      height: 104rpx;
      display: flex;
      align-items: center;
      padding: 0 40rpx;
      border-radius: 99px;
    }

    .style1 {
      background-color: #f9f8f9;
    }

    .style2 {
      border: 1px solid #999;
    }

    .style3 {
      border-bottom: 1px solid #efefef;
    }

    .password {
      margin-top: 40rpx;
      width: 100%;
      height: 104rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 40rpx;
      background-color: #f9f8f9;
      border-radius: 99px;
    }

    .btn {
      width: 100%;
      height: 100rpx;
      margin-top: 80rpx;
      border-radius: 50rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(90deg, #f22300, #ff4c17);
      font-size: 32rpx;
      color: #fff;
    }
    .applebtn {
      background: #000;
    }
    .disabled {
      background: #fcc1be;
    }

    .ways {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 40rpx;
      font-size: 28rpx;
      color: #666;
    }

    .others {
      margin-top: 100rpx;

      .title {
        display: flex;
        align-items: center;
        justify-content: center;

        span:nth-child(1) {
          width: 220rpx;
          height: 1px;
          background-color: #efefef;
        }

        span:nth-child(2) {
          font-size: 24rpx;
          color: #ccc;
          margin: 0 20rpx;
        }

        span:nth-child(3) {
          width: 220rpx;
          height: 1px;
          background-color: #efefef;
        }
      }

      .methods {
        margin-top: 100rpx;
        display: flex;
        align-items: center;
        justify-content: space-around;

        .method {
          display: flex;
          flex-direction: column;
          align-items: center;

          .pic {
            width: 96rpx;
            height: 96rpx;
            border-radius: 50%;
            overflow: hidden;

            image {
              width: 100%;
              height: 100%;
            }
          }

          span {
            font-size: 24rpx;
            color: #a2a2a2;
            margin-top: 10rpx;
          }
        }
      }
    }

    .welcome {
      font-size: 56rpx;
      font-weight: 600;
      color: #262626;
      margin-bottom: 80rpx;
    }
  }

  .warning {
    display: flex;
    width: 100%;
    font-size: 24rpx;
    color: #bebebe;
    margin-top: 40rpx;
    .content {
      margin-left: 20rpx;
    }
  }
}
.login-tab {
    display: flex;
    justify-content: space-around;
    align-items: center;
    border-bottom: 1px solid #efefef;
    margin-bottom: 30rpx;
}
.login-tab div {
    color: #999;
    font-size: 40rpx;
    padding-bottom: 20rpx;
}
.login-tab div.current {
    color: #333;
    border-bottom: 1px solid #f22300;
}
</style>
